﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace wUniApp.MVC.App_Data
{
  public class wDbContext<T> : DbContextBase where T : class
  {
    public IDbSet<T> GetDbSet()
    {
      Type type = typeof(T);
      if (type == typeof(Customer))
      {
        return (IDbSet<T>)Customers;
      }
      if (type == typeof(Product))
      {
        return (IDbSet<T>)Products;
      }
      if (type == typeof(Execution))
      {
        return (IDbSet<T>)Executions;
      }
      if (type == typeof(InheritanceProcedure))
      {
        return (IDbSet<T>)InheritanceProcedures;
      }
      return null;
    }

    /// <summary>
    /// Posledna exception, predpokladam ze nebude object multithredovo extremne vyuzivany, na moje ucely teraz postacuje ;-)
    /// </summary>
    public Exception LastException { get; protected set; }
    
    // Zakladne "C(R)UD" metody
    
    public bool Create(T item)
    {
      try
      {
        GetDbSet().Add(item);
        SaveChanges();
        return true;
      }
      catch (Exception ex)
      {
        LastException = ex;
        return false;
      }
    }

    public bool Update(T item)
    {
      try
      {
        Entry(item).State = EntityState.Modified;
        SaveChanges();
        return true;
      }
      catch (Exception ex)
      {
        LastException = ex;
        return false;
      }
    }

    public bool Delete(int key)
    {
      try
      {
        var dbs = GetDbSet();
        T item = dbs.Find(key);
        dbs.Remove(item);
        SaveChanges();
        return true;
      }
      catch (Exception ex)
      {
        LastException = ex;
        return false;
      }
    }

    public T Find(int key)
    {
      return GetDbSet().Find(key);
    }

  }
}